package net.organizer.ui.actionhandler;

import java.util.logging.Logger;

import javax.servlet.http.HttpServletRequest;

import net.organizer.dao.Domain;
import net.organizer.dao.Org;
import net.organizer.ui.actionhandler.message.UnknownEntityMessage;

import org.json.JSONObject;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.NotFoundException;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

public class OrgGetOneActionHandler extends ActionHandlerBase {
	private static final Logger logger = Logger.getLogger(OrgGetOneActionHandler.class.getName());
	
	@Override
	public void handleAction(HttpServletRequest req, JSONObject respJSONObject) throws Exception {
		logger.fine("handleAction");
		long id = getParamValueAsLong(req, "id", true);
		try{
			Domain domain = new Domain();
			domain.setName("domain1");
			Objectify ofy = ObjectifyService.begin();
			logger.fine("handleAction...<----------- org id: " + id);
			Key<Org> key = Org.getKey(domain, id);
			logger.fine("org key: " + key);
			Org org = ofy.get(key);
			logger.fine("org: " + org);
			if(org.getParentOrgKey() != null){
				logger.fine("get the parentOrgKey: " + org.getParentOrgKey());
				Org parentOrg = ofy.get(org.getParentOrgKey());
				logger.fine("parentOrg: " + parentOrg);
				org.setParentOrg(parentOrg);
			}
			logger.fine("get org persons");
			org.loadOrgPersons(ofy, domain);

			respJSONObject.put("org", org.toJSONObject());
		}catch(NotFoundException e){
			logger.fine("not found exception : " + e);
			new UnknownEntityMessage(id, respJSONObject);
		}
	}
}
